package com.netease.nim.uikit.business.recent.holder;

import android.content.ComponentName;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.nim.uikit.R;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.business.recent.RecentContactsCallback;
import com.netease.nim.uikit.business.recent.adapter.RecentContactAdapter;
import com.netease.nim.uikit.business.session.emoji.MoonUtil;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nim.uikit.common.CommonUtil;
import com.netease.nim.uikit.common.framework.infra.Handlers;
import com.netease.nim.uikit.common.ui.drop.DropFake;
import com.netease.nim.uikit.common.ui.drop.DropManager;
import com.netease.nim.uikit.common.ui.imageview.HeadImageView;
import com.netease.nim.uikit.common.ui.recyclerview.adapter.BaseQuickAdapter;
import com.netease.nim.uikit.common.ui.recyclerview.holder.BaseViewHolder;
import com.netease.nim.uikit.common.ui.recyclerview.holder.RecyclerViewHolder;
import com.netease.nim.uikit.common.util.BadgeView;
import com.netease.nim.uikit.common.util.sys.ScreenUtil;
import com.netease.nim.uikit.common.util.sys.TimeUtil;
import com.netease.nim.uikit.impl.cache.UIKitLogTag;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.friend.FriendService;
import com.netease.nimlib.sdk.friend.model.Friend;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.MsgStatusEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.superteam.SuperTeam;
import com.netease.nimlib.sdk.team.model.Team;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.utils.KLog;

public abstract class RecentViewHolder extends RecyclerViewHolder<BaseQuickAdapter, BaseViewHolder, RecentContact> {

    public RecentViewHolder(BaseQuickAdapter adapter) {
        super(adapter);
    }

    private int lastUnreadCount = 0;

    protected FrameLayout portraitPanel;

    protected HeadImageView imgHead;

    protected TextView tvNickname;

    protected TextView tvMessage;

    protected TextView tvDatetime;

    protected TextView tvGoTo;

    // 消息发送错误状态标记，目前没有逻辑处理
    protected ImageView imgMsgStatus;

  //  protected View bottomLine;

    //protected View topLine; Location

    // 未读红点（一个占坑，一个全屏动画）
    protected com.netease.nim.uikit.util.BadgeView tvUnread;

    private ImageView imgUnreadExplosion;

    protected TextView tvOnlineState;

    private static Integer labelWidth;

    private int pos;
    // 子类覆写
    protected abstract String getContent(RecentContact recent);

    @Override
    public void convert(BaseViewHolder holder, RecentContact data, int position, boolean isScrolling) {
        inflate(holder, data);
        refresh(holder, data, position);
        this.pos = position;
    }

    public void inflate(BaseViewHolder holder, final RecentContact recent) {
        this.tvGoTo = holder.getView(R.id.tv_goto);
        this.portraitPanel = holder.getView(R.id.portrait_panel);
        this.imgHead = holder.getView(R.id.img_head);
        this.tvNickname = holder.getView(R.id.tv_nickname);
        this.tvMessage = holder.getView(R.id.tv_message);
        this.tvUnread = holder.getView(R.id.unread_number_tip);
        this.imgUnreadExplosion = holder.getView(R.id.unread_number_explosion);
        this.tvDatetime = holder.getView(R.id.tv_date_time);
        this.imgMsgStatus = holder.getView(R.id.img_msg_status);
       // this.bottomLine = holder.getView(R.id.bottom_line);
      //  this.topLine = holder.getView(R.id.top_line);
        this.tvOnlineState = holder.getView(R.id.tv_online_state);
        holder.addOnClickListener(R.id.unread_number_tip);
        portraitPanel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getCallback().onUserItemClick(recent);
            }
        });
        holder.getView(R.id.item_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCallback().onItemClick(recent);
            }
        });
        holder.getView(R.id.item_layout).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                getCallback().showLongClickMenu(recent,pos);
                return false;
            }
        });

        holder.getView(R.id.btnDel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                final MsgService msgService = NIMClient.getService(MsgService.class);
//                msgService.deleteRecentContact(recent);
//                msgService.clearChattingHistory(recent.getContactId(), recent.getSessionType());
                String json =  JSONObject.toJSONString(recent);
                KLog.d("bbbbbbb  shanchu  "+json);

                Messenger.getDefault().send(recent.getContactId(),"shanchu");
            }
        });

        holder.getView(R.id.btnJiechu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //String json =  JSONObject.toJSONString(recent);
                KLog.d("bbbbbbbbbbbbbbbbbbbbbbb  jiechu  ");
                Messenger.getDefault().send(recent.getContactId(),"jiechu");
            }
        });
//        //this.tvUnread.setTouchListener(new DropFake.ITouchListener() {
//
//            @Override
//            public void onDown() {
//                DropManager.getInstance().setCurrentId(recent);
//                DropManager.getInstance().down(tvUnread, tvUnread.getText());
//            }
//
//            @Override
//            public void onMove(float curX, float curY) {
//                DropManager.getInstance().move(curX, curY);
//            }
//
//            @Override
//            public void onUp() {
//                DropManager.getInstance().up();
//            }
//        });
    }

    public void refresh(BaseViewHolder holder, RecentContact recent, final int position) {
        // unread count animation
        boolean shouldBoom = lastUnreadCount > 0 && recent.getUnreadCount() == 0; // 未读数从N->0执行爆裂动画;
        lastUnreadCount = recent.getUnreadCount();
        updateBackground(holder, recent, position);
        loadPortrait(recent);
        updateNickLabel(UserInfoHelper.getUserTitleName(recent.getContactId(), recent.getSessionType()));
        updateOnlineState(recent);
        updateMsgLabel(holder, recent);
        updateNewIndicator(recent);


        NimUserInfo user = NIMClient.getService(UserService.class).getUserInfo(recent.getContactId());

        KLog.d("RecentViewHolder","user:"+user);

        if (user!=null &&  user.getExtensionMap()!=null){

            KLog.d("RecentViewHolder","user getExtensionMap :"+JSON.toJSONString( user.getExtensionMap()));

           // System.out.println(JSON.toJSONString( user.getExtensionMap()));
        }


        Friend friend = NIMClient.getService(FriendService.class).getFriendByAccount(recent.getContactId());

        if(friend.getServerExtension() !=null ){
            KLog.d("RecentViewHolder","server "+friend.getServerExtension());
        }
    //    KLog.d("RecentViewHolder","recent.getContactId():"+recent.getContactId()+" getServerExtension "+friend.getServerExtension()+" getExtension: "+friend.getExtension());
        if (friend!=null && friend.getExtension()!=null){
            String uid = NimUIKit.getAccount();

            KLog.d("RecentViewHolder","friend getExtensionMap :"+JSON.toJSONString(friend.getExtension()));

          //  KLog.d("RecentViewHolder","friend getServerExtensionMap :"+friend.getServerExtension());
            String InviteUid="",InviteesUid="",InviteDesc="",InviteesDesc="";
            if (friend.getExtension().get("InviteUid")!=null ){
                InviteUid = friend.getExtension().get("InviteUid").toString();
            }
            if (friend.getExtension().get("InviteesUid")!=null){
                InviteesUid = friend.getExtension().get("InviteesUid").toString();
            }
            if (friend.getExtension().get("InviteDesc")!=null){
                InviteDesc = friend.getExtension().get("InviteDesc").toString();
            }
            if (friend.getExtension().get("InviteesDesc")!=null){
                InviteesDesc = friend.getExtension().get("InviteesDesc").toString();
            }

            if (InviteUid.equals(uid)){
                KLog.d("RecentViewHolder","InviteDesc:"+InviteDesc);
                tvGoTo.setText(InviteDesc);
            }else{
                KLog.d("RecentViewHolder","InviteesDesc:"+InviteesDesc);
                tvGoTo.setText(InviteesDesc);
            }

        }else {
            tvGoTo.setText("关系获取失败");
            KLog.d("RecentViewHolder","HTtvGoTo:");
        }
        if (shouldBoom) {
            Object o = DropManager.getInstance().getCurrentId();
            if (o instanceof String && o.equals("0")) {
                imgUnreadExplosion.setImageResource(R.drawable.nim_explosion);
                imgUnreadExplosion.setVisibility(View.VISIBLE);
                Handlers.sharedHandler(holder.getContext()).post(() -> {
                    ((AnimationDrawable) imgUnreadExplosion.getDrawable()).start();
                    // 解决部分手机动画无法播放的问题（例如华为荣耀）
                    getAdapter().notifyItemChanged(getAdapter().getViewHolderPosition(position));
                });
            }
        } else {
            imgUnreadExplosion.setVisibility(View.GONE);
        }
    }

    private void updateBackground(BaseViewHolder holder, RecentContact recent, int position) {
       // topLine.setVisibility(getAdapter().isFirstDataItem(position) ? View.GONE : View.VISIBLE);
        //bottomLine.setVisibility(getAdapter().isLastDataItem(position) ? View.VISIBLE : View.GONE);
        holder.getConvertView().setBackgroundResource(recent == null || NIMClient.getService(MsgService.class)
                .isStickTopSession(recent.getContactId(), recent.getSessionType()) ?
                R.drawable.nim_recent_contact_sticky_selecter : R.drawable.nim_touch_bg);
    }

    protected void loadPortrait(RecentContact recent) {
        // 设置头像
        if (recent.getSessionType() == SessionTypeEnum.P2P) {
            imgHead.loadBuddyAvatar(recent.getContactId());
        } else if (recent.getSessionType() == SessionTypeEnum.Team) {
            Team team = NimUIKit.getTeamProvider().getTeamById(recent.getContactId());
            imgHead.loadTeamIconByTeam(team);
        } else if (recent.getSessionType() == SessionTypeEnum.SUPER_TEAM) {
            SuperTeam team = NimUIKit.getSuperTeamProvider().getTeamById(recent.getContactId());
            imgHead.loadSuperTeamIconByTeam(team);
        } else if (recent.getSessionType() == SessionTypeEnum.Ysf) {
            imgHead.setImageResource(R.drawable.nim_ic_ysf_default_icon);
        }
    }

    private void updateNewIndicator(RecentContact recent) {
        int unreadNum = recent.getUnreadCount();
        KLog.d("unreadNum    "+unreadNum+" aa"+unreadCountShowRule(unreadNum));
        tvUnread.setVisibility(unreadNum > 0 ? View.VISIBLE : View.GONE);
      //  tvUnread.setBadgeText(unreadCountShowRule(unreadNum));
//        tvUnread.setBadgeText(10);
        tvUnread.setBadgeNum(unreadNum);
        tvUnread.redraw();
    }

    private void updateMsgLabel(BaseViewHolder holder, RecentContact recent) {
        // 显示消息具体内容
        MoonUtil.identifyRecentVHFaceExpressionAndTags(holder.getContext(), tvMessage, getContent(recent), -1, 0.45f);
        //tvMessage.setText(getContent());
        MsgStatusEnum status = recent.getMsgStatus();
        if (status == null) {
            imgMsgStatus.setVisibility(View.GONE);
        } else {
            switch (status) {
                case fail:
                    imgMsgStatus.setImageResource(R.drawable.nim_g_ic_failed_small);
                    imgMsgStatus.setVisibility(View.VISIBLE);
                    break;
                case sending:
                    imgMsgStatus.setImageResource(R.drawable.nim_recent_contact_ic_sending);
                    imgMsgStatus.setVisibility(View.VISIBLE);
                    break;
                default:
                    imgMsgStatus.setVisibility(View.GONE);
                    break;
            }
        }
        String timeString = TimeUtil.getTimeShowString(recent.getTime(), true);
        tvDatetime.setText(timeString);
    }

    protected String getOnlineStateContent(RecentContact recent) {
        return "";
    }

    protected void updateOnlineState(RecentContact recent) {
        if (recent.getSessionType() == SessionTypeEnum.Team || recent.getSessionType() == SessionTypeEnum.SUPER_TEAM) {
            tvOnlineState.setVisibility(View.GONE);
        } else {
            String onlineStateContent = getOnlineStateContent(recent);
            if (TextUtils.isEmpty(onlineStateContent)) {
                tvOnlineState.setVisibility(View.GONE);
            } else {
                tvOnlineState.setVisibility(View.VISIBLE);
                tvOnlineState.setText(getOnlineStateContent(recent));
            }
        }
    }

    protected void updateNickLabel(String nick) {
        if (labelWidth == null) {
            labelWidth = ScreenUtil.screenWidth - ScreenUtil.dip2px(120); // 减去固定的头像和时间宽度;
        }
        if (labelWidth > 0) {
            tvNickname.setMaxWidth(labelWidth);
        }
        tvNickname.setText(nick);
    }

    protected String unreadCountShowRule(int unread) {
        unread = Math.min(unread, 99);
        return String.valueOf(unread);
    }

    protected RecentContactsCallback getCallback() {
        return ((RecentContactAdapter) getAdapter()).getCallback();
    }
}
